﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Furion;
using SqlSugar;

namespace PMP.Core.SqlSugar;


/// <summary>
/// 数据库上下文对象
/// </summary>
public static class DbContext
{
    /// <summary>
    /// SqlSugar 数据库实例
    /// </summary>
    public static readonly SqlSugarScope Instance = new(
        // 读取 appsettings.json 中的 ConnectionConfigs 配置节点
        App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs")
        , db =>
        {
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                var sqlStr = UtilMethods.GetSqlString(DbType.SqlServer, sql, pars);
                App.PrintToMiniProfiler("SQL", "执行", sqlStr);
                Console.WriteLine($"--------- [{DateTime.Now}] Sql ---------");
                Console.WriteLine(sqlStr);
            };
            
            var config = db.CurrentConnectionConfig;
            config.IsAutoCloseConnection = true;
            // 建表技巧,自动Nullable 
            config.ConfigureExternalServices = new ConfigureExternalServices
            {
                EntityService = (info, columnInfo) =>
                {
                    if (columnInfo.IsPrimarykey == false &&
                        new NullabilityInfoContext().Create(info).WriteState is NullabilityState.Nullable)
                    {
                        columnInfo.IsNullable = true;
                    }
                }
            };
            
        });
}
